import React from "react";

import { Button, Table, Input, Icon, Tag } from "antd";

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            subscribeList: [],
            message: undefined,
            msgList: [],
            pageSize: 20,
            current: 1
        };

        this.subscribe = this.subscribe.bind(this);
        this.unSubscribe = this.unSubscribe.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        const {message, msgList} = this.state;
        if (nextProps.message && nextProps.message !== message) {
            msgList.unshift(nextProps.message);
            this.setState({
                msgList,
                message: nextProps.message
            });
        }
    }

    subscribe() {
        const { subscribe } = this.props;
        const { subscribeList, text } = this.state;
        if(text == undefined || text.length == 0) {
            return;
        }

        subscribeList.push(text);
        subscribe(text);
        this.setState({ subscribeList, text: "" });
    }

    unSubscribe(text, index) {
        const { unSubscribe } = this.props;
        const { subscribeList } = this.state;
        subscribeList.splice(index, 1);
        this.setState({ subscribeList });
        unSubscribe(text);
    }

    render() {
        const { connect } = this.props;
        const {msgList = [], pageSize, current, subscribeList, text } = this.state;
        const columns = [
            {
                title: '序号',
                render: (text, record, index) => msgList.length - (pageSize * (current - 1) + index),
                width: 80
            },{
                title: '主题',
                dataIndex: 'destinationName',
                key: 'destinationName',
                width: 300
            }, {
                title: '消息数据',
                dataIndex: 'payloadString',
                key: 'payloadString'
            }];

        const pagination = {
            total: msgList.length,
            current,
            pageSize,
            onChange: (current) => this.setState({ current })
        };// $IOT/evm/datapoint/location

        return (
            <div>
                <div style={ {width: "320px"} }>
                    <Input addonAfter={<Icon type="pushpin" onClick={ this.subscribe } />} value={ text } onChange={ e => this.setState({ text: e.target.value }) } disabled={ !connect } />
                </div>
                <div className="mt20">
                    {
                        subscribeList.map((item, index) => (<Tag key={item} closable onClose={ () => this.unSubscribe(item, index) } color="#87d068">{ item }</Tag>))
                    }
                </div>
                <Table columns={ columns } dataSource={ msgList } pagination={ pagination } bordered className="mt20" />
            </div>
            );
    }
}

export default Main;